package com.margo.project.security.config;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.margo.project.security.util.JwtUtils;

/**
 * Spring security登录成功处理类,返回jwt
 * @author fangxingbang
 *
 */
@Component
public class MargoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		logger.info("登录成功");
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");

		// 从authentication中获取用户信息
		final JwtUser userDetail = (JwtUser) authentication.getPrincipal();
		// 生成jwt
		String token = JwtUtils.createJwtToken(userDetail.getUsername());
		response.addHeader("token", "Bearer " + token);
		response.getWriter().write("{\"result\":\"ok\"}");
		response.getWriter().flush();

	}

}
